﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PaymentHelper.Core.RelatedObject;
using PaymentHelper.Core.ExceptionHandler;

namespace PaymentHelper.Core.Extension
{
    public abstract class BaseExtension:IExtension
    {
        protected ExtensionDescriptor _descriptor;
        protected IList<PHSettingItem> _settings;

        /// <summary>
        /// Gets and set settings
        /// </summary>
        public IList<PHSettingItem> Settings
        {
            get { return _settings; }
            set { _settings = value; }
        }
        
        /// <summary>
        /// Gets and sets descriptor
        /// </summary>
        public ExtensionDescriptor Descriptor
        {
            get { return _descriptor; }
            set { _descriptor = value; }
        }

        public virtual bool Install()
        {
            if (_descriptor.Installed == true)
                return false;
            return ExtensionManager.Install(_descriptor.SystemName);
        }

        public virtual bool UnInstall()
        {
            if (_descriptor.Installed == false)
                return false;

            return ExtensionManager.UnInstall(_descriptor.SystemName);
        }

        public virtual IList<PHSettingItem> LoadSettings()
        {
            _settings = ExtensionManager.LoadSettings(Descriptor.SystemName);

            return _settings;
        }

        public virtual bool SaveSettings()
        {
            return ExtensionManager.SaveSettings(Descriptor.SystemName, Settings);
        }

        public dynamic GetSetting(string nameSetting)
        {
            if (_settings == null || _settings.Count == 0)
                LoadSettings();

            if (string.IsNullOrEmpty(nameSetting))
                throw new PaymentHelperException(ExceptionLevel.Warning, "BaseExtension-GetSetting", "Name of setting is null. Loading specified setting failed !");

            var attr = Settings.SingleOrDefault(at => at.Name.Equals(nameSetting, StringComparison.InvariantCultureIgnoreCase));
            
            return (attr != null) ? attr.Value : null;
        }
    }
}
